package com.ygqh.baby.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.mapper.YgGroupMapper;
import com.ygqh.baby.mapper.YgSkuMapper;
import com.ygqh.baby.mapper.YgSkuMaterialMapper;
import com.ygqh.baby.model.AdminPack;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.YgSkuMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.*;

@Service
public class YgSkuMaterialServiceImpl implements YgSkuMaterialService {

    @Autowired
    private YgSkuMaterialMapper ygSkuMaterialMapper;
    @Autowired
    private YgSkuMapper ygSkuMapper;
    @Autowired
    private YgGroupMapper ygGroupMapper;


    @Override
    public List<YgSkuMaterial> find() {
        YgSkuMaterialExample example = new YgSkuMaterialExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygSkuMaterialMapper.selectByExample(example);
    }

    @Override
    public int findCount() {
        YgSkuMaterialExample example = new YgSkuMaterialExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygSkuMaterialMapper.countByExample(example);
    }

    @Override
    public YgSkuMaterial findById(Long id) {
        return ygSkuMaterialMapper.selectByPrimaryKey(id);
    }


    @Override
    public int save(YgSkuMaterial ygSkuMaterial) {
        return ygSkuMaterialMapper.insertSelective(ygSkuMaterial);
    }

    @Override
    public int update(YgSkuMaterial ygSkuMaterial) {
        return ygSkuMaterialMapper.updateByPrimaryKeySelective(ygSkuMaterial);
    }


    @Override
    public int deleteSoft(Long[] ids) {
        Assert.notEmpty(ids);
        YgSkuMaterialExample example = new YgSkuMaterialExample();
        example.createCriteria().andIdIn(Arrays.asList(ids));
        YgSkuMaterial record = new YgSkuMaterial();
        record.setStatus(DataStatus.Delete);

        return ygSkuMaterialMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int deleteSoft(Long id) {
        return this.deleteSoft(new Long[]{id});
    }

    @Override
    public int saveOrUpdate(YgSkuMaterial ygSkuMaterial) {
        int r = 0;
        if (ygSkuMaterial.getId() != null) {
            r = this.update(ygSkuMaterial);
        } else {
            r = this.save(ygSkuMaterial);
        }
        return r;
    }

    @Override
    public List<YgSkuMaterial> findSkuCostByProductId(String productCode) {


        return ygSkuMaterialMapper.selectSkuByProductId(productCode);
    }

    @Override
    public Message saveOrUpdate(List<YgSkuMaterial> list, String createBy) {
        List<YgSku> skulist = new ArrayList<YgSku>();

        for (YgSkuMaterial ygSkuMaterial : list) {

            ygSkuMaterial.setStatus(DataStatus.Valid);
            YgSkuMaterialExample example = new YgSkuMaterialExample();
            example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andSkuCodeEqualTo(ygSkuMaterial.getSkuCode());
            int i = ygSkuMaterialMapper.countByExample(example);
            if (i == 0) {
                ygSkuMaterial.setCreateBy(createBy);
                ygSkuMaterial.setCreateTime(new Date());
                ygSkuMaterialMapper.insert(ygSkuMaterial);
            } else {
                ygSkuMaterial.setUpdateBy(createBy);
                ygSkuMaterial.setUpdateTime(new Date());
                ygSkuMaterialMapper.updateByExampleSelective(ygSkuMaterial, example);
            }
            //更新sku表的成本
            YgSku sku = new YgSku();
            sku.setSkuCode(ygSkuMaterial.getSkuCode());
            sku.setCostPrice(ygSkuMaterial.getCostPrice());
            skulist.add(sku);

        }
        ygSkuMapper.updateCostPrice(skulist);


        return Message.success("更新成功");
    }

    @Override
    public Message saveSkuCostByGroupCode(List<YgSkuMaterial> list, String createBy, Long groupId) {
        List<YgSku> skulist = new ArrayList<YgSku>();
        //根据分组code 获取组对应的成本和成本组成
        YgGroup group = ygGroupMapper.selectByPrimaryKey(groupId);
        //只有新增的sku 才处理成本
        for (YgSkuMaterial ygSkuMaterial : list) {
            ygSkuMaterial.setCreateBy(createBy);
            ygSkuMaterial.setCreateTime(new Date());
            ygSkuMaterial.setStatus(DataStatus.Valid);
            YgSkuMaterialExample example = new YgSkuMaterialExample();
            example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andSkuCodeEqualTo(ygSkuMaterial.getSkuCode());
            int i = ygSkuMaterialMapper.countByExample(example);
            if (i == 0) {
                ygSkuMaterial.setCostPrice(group.getCostPrice());
                ygSkuMaterial.setExtMaterial(group.getExtMaterial());
                ygSkuMaterialMapper.insert(ygSkuMaterial);
            } else {
                ygSkuMaterialMapper.updateByExampleSelective(ygSkuMaterial, example);
            }
            //更新sku表的成本
            YgSku sku = new YgSku();
            sku.setSkuCode(ygSkuMaterial.getSkuCode());
            sku.setCostPrice(ygSkuMaterial.getCostPrice());
            skulist.add(sku);

        }
        if (skulist.size() > 0)
            ygSkuMapper.updateCostPrice(skulist);
        return Message.success("更新成功");
    }

    @Override
    public void setSkuMaterialByContractCode(List<AdminContractDetail> adminContractDetails) {
        //根据extMaterial 判断是否已经维护包装成本
        double totalPrice = 0;
        double baozhuang = 0;
        double fengkou = 0;
        Map<String, Object> maps = null;
        JSONObject jsonObj = new JSONObject();
        List<Map<String, Object>> tiezhis = new ArrayList<Map<String, Object>>();
        Map<String, Object> temp = new HashMap<String, Object>();
        //加上SKU进货价，更新成本
        List<YgSkuMaterial> skus = new ArrayList<YgSkuMaterial>();

        for (AdminContractDetail detail : adminContractDetails) {
            totalPrice = 0;
            String extMaterial = detail.getGroup().getExtMaterial();
            if (extMaterial != null) {
                maps = JSONObject.parseObject(extMaterial, Map.class);
                //循环
                for (Map.Entry<String, Object> entry : maps.entrySet()) {

                    if (!entry.getKey().equals("tiezhi") && !entry.getKey().equals("skuCost")) {
                        AdminPack pack = JSON.parseObject(entry.getValue().toString(), AdminPack.class);
                        totalPrice += pack.getPrice();
                        jsonObj.put(entry.getKey(), entry.getValue());
                    }
                    if (entry.getKey().equals("tiezhi")) {
                        jsonObj.put(entry.getKey(), entry.getValue());
                        JSONArray jsonArray = JSON.parseArray(entry.getValue().toString());
                        List<AdminPack> packList = JSON.parseObject(jsonArray.toJSONString(), new TypeReference<List<AdminPack>>() {
                        });
                        for (AdminPack p : packList) {
                            totalPrice += p.getPrice() * p.getAmount();
                        }

                    }
                }

            }

            if (maps == null) maps = new HashMap<String, Object>();
            jsonObj.put("skuCost", detail.getPrice());
            YgSkuMaterial skuMaterial = new YgSkuMaterial();
            skuMaterial.setSkuCode(detail.getSkuCode());
            skuMaterial.setExtMaterial(jsonObj.toJSONString());
            skuMaterial.setCostPrice(detail.getPrice().add(new BigDecimal(totalPrice)));
            skus.add(skuMaterial);
        }
        ygSkuMaterialMapper.updateSkuCostByList(skus);

    }

    @Override
    public YgSkuMaterial findSkuByBarCode(String barCode) {
        return ygSkuMaterialMapper.selectSkuByBarCode(barCode);

    }

    @Override
    public ResultSet<YgSkuMaterial> search(QueryInfo queryInfo,
                                           String productCode, String skuCode, String productName, String barCode) {
        List<YgSkuMaterial> list = ygSkuMaterialMapper.selectSuper(queryInfo, productCode, skuCode, productName, barCode);
        int count = ygSkuMaterialMapper.countSuper(productCode, skuCode, productName, barCode);
        ResultSet<YgSkuMaterial> resultSet = new ResultSet<YgSkuMaterial>(count, list);
        return resultSet;
    }

    @Override
    public void updateSkuMaterial(List<YgSkuMaterial> ygSkuMaterial,
                                  String trueName) {
        ygSkuMaterialMapper.updateBatchSkuMaterial(ygSkuMaterial);
    }

    @Override
    public List<YgSkuMaterial> findSkuByBarCodes(List<String> barCodes) {
        return ygSkuMaterialMapper.findSkuByBarCodes(barCodes);
    }

    @Override
    public YgSkuMaterial findBySkuCode(String skuCode) {
        return ygSkuMaterialMapper.selectBySkuCode(skuCode);
    }

    @Override
    public void saveBatchSkuCost(List<YgSkuMaterial> ygSkuMaterials) {
        ygSkuMaterialMapper.saveBatchSkuCost(ygSkuMaterials);
    }

    @Override
    public List<YgSkuMaterial> findListBySkuCode(List<String> skuCodeList) {
        Assert.notEmpty(skuCodeList, "SKU编码 skuCodeList 不能为空");
        return ygSkuMaterialMapper.selectListBySkuCode(skuCodeList);
    }

    @Override
    public int updateCostPriceBatch(List<YgSkuMaterial> costList, String trueName) {
        return ygSkuMaterialMapper.updateCostPriceBatch(costList,trueName,new Date());
    }

    @Override
    public int updateBarcodeBatch(List<YgSkuMaterial> list, String trueName) {
        return ygSkuMaterialMapper.updateBarcodeBatch(list,trueName,new Date());
    }

}

